package com.databasteknik.krustykookiez;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;

public class Production extends JPanel implements ActionListener {
	private static final long serialVersionUID = 4858129803337753322L; // WIN!
	private Database db;
	private ArrayList<String> recipes;
	private ArrayList<JLabel> labels;
	private ArrayList<JTextField> fields;

	public Production(Database database) {
		this.db = database;
		recipes = db.fetchRecipes();
		labels = new ArrayList<JLabel>();
		fields = new ArrayList<JTextField>();
		JPanel selector = new JPanel();
		selector.setLayout(new GridLayout(recipes.size(), 2));
		for (int i = 0; i < recipes.size(); i++) {
			labels.add(new JLabel(recipes.get(i)));
			fields.add(new JTextField("0"));
		}
		for (int i = 0; i < labels.size(); i++) {
			selector.add(labels.get(i));
			selector.add(fields.get(i));
		}
		this.setLayout(new BorderLayout());
		JButton button = new JButton("Produce!");
		button.addActionListener(this);
		this.add(selector, BorderLayout.NORTH);
		this.add(button, BorderLayout.SOUTH);
		this.setVisible(true);
	}

	public void actionPerformed(ActionEvent arg0) {
		for (int i = 0; i < recipes.size(); i++) {
			int amount = getValue(fields.get(i).getText());
			if (amount < 0) {
				JOptionPane.showMessageDialog(this, "Illegal input");
			} else if (amount != 0) {
				boolean succeeded = db.producePallets(recipes.get(i), amount);
				if(succeeded) {
					JOptionPane.showMessageDialog(this, "" + amount + " pallets of " + recipes.get(i) + " produced.");
				} else {
					JOptionPane.showMessageDialog(this, "Could not produce " + amount + " pallets of " + recipes.get(i) + ".");
				}
			}
		}
	}

	private int getValue(String s) {
		int number = 0;
		try {
			number = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			number = -1;
		}
		return number;
	}
}